const db = require("../db/index");
const bcrypt = require("bcryptjs");

const jwt = require("jsonwebtoken");
const config = require("../config");

exports.register = (req, res) => {
  const userInfo = req.body;

  // 判断用户名和密码是否为空  , 已优化，应该使用专有的中间件 joi进行判断
  // if (!userInfo.username || !userInfo.password) {
  //   return res.cc("username and password can not be empty");
  // }

  // 判断用户名是否已存在？
  const sqlStr = "select * from ev_users where username = ?";
  db.query(sqlStr, userInfo.username, (err, results) => {
    if (err) {
      return res.cc(err);
    }

    if (results.length > 0) {
      return res.cc("username already been used, please try another one");
    }

    // 对密码进行加密
    userInfo.password = bcrypt.hashSync(userInfo.password, 10);
    const sqlStr2 = "insert into ev_users set ?";
    db.query(
      sqlStr2,
      { username: userInfo.username, password: userInfo.password },
      (err, results) => {
        if (err) return res.cc(err);

        if (results.affectedRows !== 1)
          return res.cc("register failed, please try later");

        res.cc("resigstered successfully", 200);
      }
    );
  });
};

exports.login = (req, res) => {
  const userInfo = req.body;

  // 判断用户名和密码是否为空  , 已优化，应该使用专有的中间件 joi进行判断
  // if (!userInfo.username || !userInfo.password) {
  //   return res.cc("username and password can not be empty");
  // }

  // 判断用户名是否存在？
  const sqlStr = "select * from ev_users where username = ?";
  db.query(sqlStr, userInfo.username, (err, results) => {
    if (err) {
      return res.cc(err);
    }

    if (results.length !== 1) {
      return res.cc("username not exist");
    }

    // 判断密码是否一致
    const compareResult = bcrypt.compareSync(
      userInfo.password,
      results[0].password
    );
    if (!compareResult) return res.cc("password is wrong");

    // 为了保护用户信息，在返回的token中应该剔除密码 和头像信息，可以用es6高级语法剔除， 扩展运算符展开对象，
    // 如果后面再跟上同名属性，则后面的值会覆盖原有属性的值

    const user = { ...results[0], password: "", user_pic: "" };

    // 对用户的信息进行加密， 生成token 字符串
    const tokenStr = jwt.sign(user, config.jwtSecretKey, {
      expiresIn: config.expiresIn,
    });

    res.send({
      status: 200,
      message: "login successfully",
      token: "Bearer " + tokenStr,
    });
  });
};
